<template>
	<view class="content">
		<u-sticky bgColor="#ffffff" v-if="listid==''">
			<u-tabs :activeStyle="{
          color: '#C1282D',
          fontWeight: 'bold', 
          transform: 'scale(1.05)',
        }" lineColor="#C1282D" :scrollable="false" style="width: 100%" :list="list1" @click="changeTab"
				:itemStyle="{ width: '40%', paddingBottom: '20rpx', height: '60rpx' }"></u-tabs>
		</u-sticky>
		<view v-if="tab == 0" class="boxItem">
			<y-input text="姓名" :inputVal="from.name" @change="change" type="name"></y-input>
			<u-line></u-line>
			<y-input text="身份证号" :inputVal="from.idcard" @change="change" type="idcard"></y-input>
			<u-line></u-line>
			<y-input text="手机号" :inputVal="from.phone" @change="change" type="phone"></y-input>
			<u-line></u-line>
			<view v-for="(item, index) in selectList" :key="index">
				<view class="bet" style="padding: 40rpx 0" @click="openModal(index, item)">
					<view class="z-text">{{ item.name }}</view>
					<view class="bet" style="color: #8e8e93; font-size: 24rpx">
						<span>
							{{ from[item.key] ? from[item.key].name : "请选择" }}
						</span>
						<u-icon size="14" name="arrow-right" color="#8E8E93"></u-icon>
					</view>
				</view>
				<u-line></u-line>
			</view>
			<y-input text="年龄" :inputVal="from.age" @change="change" type="age"></y-input>
			<u-line></u-line>
			<view v-for="(item, index) in selectList2" :key="index">
				<view class="bet" style="padding: 40rpx 0" @click="openModal(index, item)">
					<view class="z-text">{{ item.name }}</view>
					<view class="bet" style="color: #8e8e93; font-size: 24rpx">
						<span v-if="item.key!='baobei'">
							{{ from[item.key] ? from[item.key].name : "请选择" }}
						</span>
						<span v-else>{{
	          from[item.key] ? getData(from[item.key] / 1000, "date") : "请选择"
	        }}</span>
						<u-icon size="14" name="arrow-right" color="#8E8E93"></u-icon>
					</view>
				</view>
				<u-line v-if="index < textList2.length - 1"></u-line>
			</view>
		</view>
		<view v-if="tab == 1" class="boxItem">
			<view class="z-text" style="margin-bottom: 20rpx">文件导入</view>
			<view class="bet sc">
				<view class="min-text" style="margin: 0 auto" @click="chooseUpload">
					<view>
						<image src="../../static/tab1/shangchuan.png" alt="" />
					</view>
					<view style="margin-top: 20rpx">只支持xls,xlsx大小不超过10M</view>
				</view>
			</view>
			<view v-if="fileList.name" class="bet" style="margin: 20rpx 0">
				<view class="flex">
					<u-icon name="file-text" color="#7fca99" size="18"></u-icon>
					<view class="min-text">{{ fileList.name }}</view>
				</view>
				<u-icon name="close" size="18" @click="delFile"></u-icon>
			</view>
		</view>
		<view class="flexcenter">
			<button v-if="tab == 0" @click="fabu" class="button fabu">{{listid?"确定":"发布"}}</button>
			<button v-else @click="fabu" class="button fabu">上传</button>
		</view>
		<u-picker :show="show" :columns="columns" @confirm="pickerOk" @cancel="show = false"></u-picker>
		<u-datetime-picker :show="shows" v-model="timeVal" ref="picker" mode="date" :minDate="minDate" @confirm="timeOk"
			@cancel="timeCancel"></u-datetime-picker>
	</view>
</template>
<script>
	import yInput from "@/components/y-input/index";
	import {
		API_URL,
		UpLoad_URL
	} from "../../env";
import HttpRequest from "../../uni_modules/uview-ui/libs/luch-request";
	const httpRequestapi = require("@/common/httpRequest.js")
	export default {
		components: {
			yInput,
		},
		name: "tab-1",
		data() {
			return {
				type: 0,
				tab: 0,
				shows: false,
				show: false,
				timeVal: 0,
				from: {
					name: "",
					phone: "",
					wenjian: "",
					idcard:"",
					age:""
				},
				textList: ["性别"],
				selectList: [{
						name: "性别",
						key: "gender"
					},
					
				],
				textList2: [ "面试公司", "用工时间", "报备时间","报备日期"],
				selectList2: [{
						name: "面试公司",
						key: "companyList"
					},{
						name: "应聘岗位",
						key: "gangweiList"
					},{
						name: "用工形式",
						key: "yongtype"
					},
					{
						name: "报备时间",
						key: "baobeisxw"
					},
					{
						name: "报备日期",
						key: "baobei"
					},
				],
				list1: [{
						name: "新建报备",
					},
					{
						name: "文件导入",
					},
				],
				columnList: {
					gender: [{
							id: 0,
							name: "男"
						},
						{
							id: 1,
							name: "女"
						},
					],
					baobeisxw: [{
							id: 1,
							name: "上午"
						},
						{
							id: 2,
							name: "下午"
						},
					],
					companyList: [],
					gangweiList:[]
				},
				columns: [],
				selects: {},
				fileList: {},
				minDate: "",
				listid:""
			};
		},
		onLoad(options) {
			this.minDate = Number(new Date('1899-01-01'));
			this.timeVal = Math.round(new Date());
			this.type = 1; // 1文员 2项目主管
			this.getCompanyList();
			if(options.id){
				uni.setNavigationBarTitle({
					title:"编辑报备"
				})
				this.listid = options.id
				this.getDetail()
			}
		},
		watch:{
			from:{
				deep:true,
				handler(newval){
					if(this.from.idcard.length==18){
						this.from.age = this.getAgeFromId(this.from.idcard)
					}
				}
			}
		},
		methods: {
			getDetail(){
				httpRequestapi.request('/api/baobei/wendetail', 'GET', {
					id:this.listid
				}).then(resp => {
					if(resp.code==1){ 
						let data = resp.data
						this.from = {
							age:data.age,
							baobei:Number(new Date(data.baobei_time)),
							baobeisxw:{
								id:data.baobei_tinetype,
								name:data.baobei_tinetype==1?"上午":"下午"
							},
							companyList:{
								id:data.company_id,
								name:data.cname,
							},
							gangweiList:{
								id:data.gangwei_id,
								name:data.gangwei.name,
							},
							gender:{
								id:data.gender,
								name:data.gender_text,
							},
							idcard:data.idcard,
							name:data.name,
							phone:data.phone,
							wenjian:data.wenjian,
							yongtype:{
								id:data.yongtype_id,
								name:data.yname,
							}
						}
					}
				})
			},
			getAgeFromId(idNumber) {
			    if (!idNumber || idNumber.length !== 18) {
			        throw new Error('Invalid ID number');
			    }
			 
			    const today = new Date();
			    const birthDate = new Date(idNumber.substring(6, 10), idNumber.substring(10, 12) - 1, idNumber.substring(12, 14));
			 
			    let age = today.getFullYear() - birthDate.getFullYear();
			    const m = today.getMonth() - birthDate.getMonth();
			    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
			        age--;
			    }
			 
			    return age;
			},
			delFile() {
				this.fileList = {};
				this.from.wenjian = {};
			},
			async getCompanyList() {
				const data = await this.http.get("index/company");
				const res = await this.http.get("index/yongtype");
				const res2 = await this.http.get("index/gangwei");
				this.columnList.companyList = data.data;
				this.columnList.yongtype = res.data;
				this.columnList.gangweiList = res2.data;
			},
			openModal(index, item) {
				this.columns = [];
				this.selects = item;
				if (item.key != "baobei") {
					const list = [];
					console.log(this.columnList[item.key], "this.columnList[item.key]");
					this.columnList[item.key].map((item) => {
						list.push(item.name);
					});
					this.columns.push(list);
					this.show = true;
				} else {
					this.shows = true;
				}

			},
			changeTab(e) {
				this.tab = e.index;
			},
			change(e) {
				this.from[e.type] = e.val;
			},
			fabu() {
				if(this.from.name==""){
					this.toast("请输入姓名");
					return false
				}
				if(!this.from.phone){
					this.toast("请输入手机号");
					return false
				}
				if(!this.from.gender){
					this.toast("请选择性别");
					return false
				}
				if(!this.from.age){
					this.toast("请输入年龄");
					return false
				}
				if(!this.from.companyList){
					this.toast("请选择面试公司");
					return false
				}
				if(!this.from.gangweiList){
					this.toast("请选择应聘岗位");
					return false
				}
				if(!this.from.yongtype){
					this.toast("请选择用工形式");
					return false
				}
				if(!this.from.baobeisxw){
					this.toast("请选择报备时间");
					return false
				}
				if(!this.from.baobei){
					this.toast("请选择报备日期");
					return false
				}
				let params = {
					name: this.from.name,
					phone: this.from.phone,
					gender: this.from.gender?.id,
					// birth: this.from?.chusheng / 1000,
					company_id: this.from.companyList?.id,
					yongtype_id: this.from.yongtype?.id,
					baobei_time: this.from?.baobei / 1000,
					wenjian: this.from.wenjian,
					gangwei_id:this.from.gangweiList?.id,
					baobei_tinetype:this.from.baobeisxw.id,
					idcard:this.from.idcard,
					age:this.from.age
				};
				let url = "baobei/add"
				if(this.listid){
					url = "baobei/editBaobei"
					this.$set(params,"id",this.listid)
				}
				this.http.post(url, params).then((res) => {
					if (res.code == 1) {
						this.toast("发布成功");
						setTimeout(() => {
							uni.navigateBack();
						}, 1000);
					} else {
						this.toast(res.msg);
					}
				});
			},
			timeOk(e) {
				this.from[this.selects.key] = e.value;
				this.timeCancel();
				this.$refs.picker.updateColumnValue(Number(new Date()))
				this.shows = false;
			},
			timeCancel() {
				this.$refs.picker.updateColumnValue(Number(new Date()))
				this.shows = false;
			},
			pickerOk(e) {
				// console.log(this.columnList[this.selects.key]);
				this.from[this.selects.key] =
					this.columnList[this.selects.key][e.indexs[0]];
				this.show = false;
			},
			chooseUpload() {
				var that = this;
				wx.chooseMessageFile({
					count: 1,
					type: "file",
					extension: [
						".xlsx",
						".xls",
						".XLSX",
						".XLS",
						"xlsx",
						"xls",
						"XLSX",
						"XLS",
					],
					success(res) {
						const tempFilePaths = res.tempFiles;
						console.log(tempFilePaths, "tempFilePaths");
						that.fileList = tempFilePaths[0];
						uni.showLoading({
							title: "上传中",
							mask: true
						});
						for (var i in tempFilePaths) {
							wx.uploadFile({
								url: UpLoad_URL, //"https://small.shiyijia.vip/api/Common/upload", //上传的服务器地址
								filePath: tempFilePaths[i].path,
								name: "file",
								formData: {
									file: tempFilePaths[i].path,
								},

								header: {
									token: uni.getStorageSync("token"),
								},
								success: function(resp) {
									console.log(resp);
									var data = JSON.parse(resp.data);
									console.log(data);
									that.from.wenjian = data.data.url;
									console.log(that.from.wenjian, "that.from.wenjian");
									uni.hideLoading();
									setTimeout(() => {
										if (data.code == 1) {
											uni.showToast({
												title: "上传成功",
												icon: "none",
												duration: 1300,
											});
										} else {
											uni.showToast({
												title: data.message,
												icon: "none",
												duration: 2000,
											});
										}
									}, 100);
								},
								fail: function(err) {
									console.log(err);
								},
							});
						}
					},
				});
			},
		},
	};
</script>
<style lang="scss" scoped>
	.fabu {
		width: 80%;
		margin-top: 30rpx;
	}

	.sc {
		height: 300rpx;
		background-color: #f5f5f5;
		text-align: center;

		image {
			width: 66rpx;
			height: 56rpx;
		}
	}
</style>